<?php

namespace app\controllers;

use app\models\RoleAccess;

use Yii;
use app\models\Role;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

class Role_accessController extends BaseAdminController
{
    public function actionIndex()
    {
       // header("Content-type:text/html;charset=utf-8");       
    	$request = \Yii::$app->request;
    	
    	$role_id = $request->get('id');
    	
    	if(!empty($role_id))
    	{
    		$current_role = Role::findOne($role_id);
    		
    		if(!empty($current_role))
    		{
    			$roleAccess = new RoleAccess();
    			
    			$access_list = include_once Yii::$app->basePath.'/yii_admnode.php';
   						
    			foreach ($access_list as $key=>$value)
    			{
    				//先查询对应模块
    				if($roleAccess->search_role_module($role_id,$key) === true)
    				{
    					//代表有对应的模块
    					$access_list[$key]['module_auth'] = 1;//模块被授权
    				}else
    				{
    					$access_list[$key]['module_auth'] = 0;//模块被授权
    				}
    				
    				$node_list = $value['node'];
    				    				
    				foreach ($node_list as $k => $v)
    				{
    				    if($role_id != 1)
    				    {
    				        //非超级管理员
    				        if(isset($v['belong']) && $v['belong']== 'admin')
    				        {
    				            unset($node_list[$k]);
    				            continue;
    				        }  				        
    				    }
    				    
    					if($roleAccess->search_role_action($role_id,$key,$v['action']) == true)
    					{
    						$node_list[$k]['node_auth'] = 1; //方法被授权
    					}else{
    						$node_list[$k]['node_auth'] = 0;
    					}
    				}
    				
    				$access_list[$key]['node'] = $node_list;
    			}
    			
    			return $this->render('index',[
    						'current_role' => $current_role,
    						'access_list' => $access_list,
    					]);
    		}else{
    			return $this->redirect(['site/error']);
    		}
    	}else
    	{
    		return $this->redirect(['site/error']);
    	}
    }
    
    public function actionUpdate()
    {
     	$request = \Yii::$app->request;
     		     	
    	$role_id = $request->post('role_id');
    	
    	$role_access = $request->post('role_access');
    	
    	if(!empty($role_id))
    	{		
    		//删除对应的角色的数据
    		RoleAccess::deleteAll("role_id = :role_id",[':role_id' =>$role_id]);
    		
    		if(isset($role_access))
    		{
    			foreach ($role_access as $key => $value)
    			{
    				$position = strpos($key, '__');
    				$module = trim(substr($key, 0,$position));
    				$action = trim(substr($key,$position+2));
    			
    				$role_access = new RoleAccess();
    				$role_access->module = $module;
    				$role_access->action = $action;
    				$role_access->role_id = $role_id;
    				
    				$role_access->save();
    				
    			}
    		}
    		
    		return $this->redirect(['role/index']);
    		
    	}else{
    		return $this->redirect(['site/error']);
    	}
    	
    }

}
